#!/usr/bin/env bash
set -e

usage () {
    cat <<EOF >&2
usage: bump-version VERSION_NAME

Updates the version number in our Android and iOS build configs,
and in the changelog.

Example:
  bump-version 27.155
EOF
    exit 2
}

version_name="$1";
shift || usage;
shift && usage;

version_code="${version_name##*.}"
tag_name=v"${version_name}"
date="$(date --iso)"

had_uncommitted=
if ! git diff-index --quiet HEAD; then
    had_uncommitted=1
fi

perl -i -0pe '
s/versionCode \K[0-9]+/'"$version_code"'/;
s/versionName "\K[0-9.]+/'"$version_name"'/;
' android/app/build.gradle

perl -i -0pe '
s|<key>CFBundleShortVersionString</key> \s*
  <string>\K [0-9.]+
 |'"$version_name"'|xs
' ios/ZulipMobile/Info.plist

perl -i -0pe '
s/^\#\#\ Unreleased\n\K
/

## '"$version_name"' ('"$date"')
/xms
' docs/changelog.md

msg="version: Bump version to $version_name."

if [ -n "$had_uncommitted" ]; then
    {
        echo "There were uncommitted changes.  To commit:"
        echo "  git commit -am ${msg@Q}"
        # NB if tempted to use the ${...@Q} feature: it's new in bash 4.4,
        # released 2016-09, found in stretch and bionic but not xenial.
        echo
        echo "Then tag the commit:"
        echo "  git tag ${tag_name}"
        echo "inspect the result, and push:"
        echo "  git push upstream main ${tag_name}"
    } >&2
    exit 1
fi

git commit -am "$msg"

git tag "${tag_name}"

{
    echo
    echo "Committed and tagged."
    echo "Inspect the result, then push; for example:"
    echo "  git push upstream main ${tag_name}"
} >&2
